<template>
	<view :style="themeColor()" class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden">

		<block v-if="!loading && verifyInfo">
			<view class="p-[30rpx] bg-[#fff]">
				<view class="text-[var(--primary-color)] fixed top-[40rpx] right-[30rpx] flex items-center"
					@click="redirect({ url: '/app/pages/verify/record' })">
					<text class="nc-iconfont nc-icon-lishijiluV6xx !text-[28rpx] -mb-[2rpx]"></text>
					<text class="text-[26rpx] ml-[8rpx]">核销记录</text>
				</view>
				<view class="flex items-center mt-[60rpx] justify-center">
					<view class="flex justify-center items-center flex-col pr-[30rpx]">
						<image class="w-[100rpx] h-[100rpx]" :src="img('static/resource/images/verify/yanzhenghexiaoma.png')" />
						<view class="text-[26rpx] mt-[14rpx] h-[36rpx] leading-[36rpx] flex-shrink-0">验证核销码</view>
					</view>
					<image class="w-[74rpx] h-[12rpx] mb-[50rpx]" :src="img('static/resource/images/verify/youjiantou.png')" />
					<view class="flex justify-center items-center flex-col pl-[30rpx]">
						<image class="w-[100rpx] h-[100rpx]" :src="img('static/resource/images/verify/hexiao.png')" />
						<view class="text-[26rpx] mt-[14rpx] h-[36rpx] leading-[36rpx] flex-shrink-0">确定核销</view>
					</view>
				</view>
			</view>
			<view class="card-template mt-[var(--top-m)] sidebar-margin" v-if="!verifyInfo.spu">
				<view class="flex" :class="{ 'mb-[var(--top-m)]': (verifyInfo.items.length - 1 != index) }"
					v-for="(item, index) in verifyInfo.items" :key="index">
					<image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)]" mode="aspectFill" v-if="item.picUrl"
						:src="img(item.picUrl)"></image>
					<image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)]" mode="aspectFill" v-else
						:src="img('addon/tourism/tourism/member/hotel.png')"></image>
					<view class="flex flex-col flex-1 ml-[20rpx] py-[4rpx]">
						<view class="leading-[1]">
							<view class="leading-[40rpx] truncate max-w-[490rpx] text-[28rpx]">{{ item.spuName }}</view>
							<view
								class="mt-[14rpx] truncate text-[24rpx] text-[var(--text-color-light9)] leading-[28rpx] max-w-[490rpx]"
								v-if="item.properties">
								{{ skuSpecFormat(item.properties) }}
							</view>
						</view>
						<view class="text-[var(--text-color-light6)] text-[28rpx] mt-[20rpx]">x{{ item.count }}</view>
					</view>
				</view>
			</view>
			<view class="card-template mt-[var(--top-m)] sidebar-margin" v-if="verifyInfo.spu">
				<view class="py-[32rpx] relative" v-if="goodsDetail.detail" @touchmove.prevent.stop>
					<view class="flex px-[32rpx] mb-[58rpx]">

						<view class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[180rpx] h-[180rpx]">
							<u--image width="180rpx" height="180rpx" :src="img(goodsDetail.detail.sku_image)" model="aspectFill">
								<template #error>
									<image class="w-[180rpx] h-[180rpx]" :src="img('static/resource/images/diy/shop_default.jpg')"
										mode="aspectFill"></image>
								</template>
							</u--image>
						</view>
						<view class="flex flex-1 flex-col justify-between ml-[24rpx] py-[10rpx]">
							<view class="w-[100%]">
								<view class="text-[var(--price-text-color)] flex items-baseline">
									<text class="text-[32rpx] font-bold price-font">￥</text>
									<text class="text-[48rpx] price-font">{{ parseFloat(goodsDetail.detail.price).toFixed(2).split('.')[0]
									}}</text>
									<text class="text-[32rpx] mr-[6rpx] price-font">.{{
										parseFloat(goodsDetail.detail.price).toFixed(2).split('.')[1]
									}}</text>
								</view>
							</view>
							<view
								class="text-[26rpx] leading-[30rpx] text-[var(--text-color-light6)] w-[100%] max-h-[60rpx] multi-hidden"
								v-if="goodsDetail.goodsSpec && goodsDetail.goodsSpec.length">已选规格：{{ goodsDetail.detail.sku_spec_format
								}}
							</view>

						</view>
					</view>

					<scroll-view class="h-[500rpx] px-[32rpx] box-border mb-[60rpx]" scroll-y="true">
						<view :class="{ 'mt-[20rpx]': 0 != index }" v-for="(item, index) in goodsDetail.goodsSpec" :key="index">
							<view class="text-[28rpx] leading-[36rpx] mb-[24rpx]">{{ item.spec_name }}</view>
							<view class="flex flex-wrap">
								<view @click="change(subItem, index)"
									class="box-border bg-[var(--temp-bg)] text-[24rpx] px-[44rpx] text-center h-[56rpx] flex-center mr-[20rpx] mb-[20rpx] border-1 border-solid rounded-[50rpx] border-[var(--temp-bg)]"
									:class="{ '!border-[var(--primary-color)] text-[var(--primary-color)] !bg-[var(--primary-color-light)]': subItem.selected }"
									v-for="(subItem, subIndex) in item.values" :key="subIndex">
									{{ subItem.name }}
								</view>
							</view>
						</view>
						<view :class="{ 'mt-[20rpx]': true }" v-if="matchLevelInfo">
							<view class="text-[28rpx] leading-[36rpx] mb-[24rpx]">核销权益</view>
							<view class="flex flex-wrap">
								<view
									class="box-border bg-[var(--temp-bg)] text-[24rpx] px-[44rpx] text-center h-[56rpx] flex-center mr-[20rpx] mb-[20rpx] border-1 border-solid rounded-[50rpx] border-[var(--temp-bg)]"
									:class="{ '!border-[var(--primary-color)] text-[var(--primary-color)] !bg-[var(--primary-color-light)]': true }">
									拼团{{ matchLevelInfo.key }}人,翻{{ matchLevelInfo.value }}倍
								</view>
							</view>
						</view>

					</scroll-view>
				</view>
			</view>

			<!-- <view class="card-template mt-[var(--top-m)] sidebar-margin">
				<view class="title">核销信息</view>
				<view class="card-template-item justify-between">
					<text class="text-[28rpx] text-[#333]">核销类型</text>
					<view class="text-[28rpx] text-[#333]">{{ verifyInfo.type_name }}</view>
				</view>
				<view class="card-template-item justify-between" v-for="(item, index) in verifyInfo.value.content.fixed">
					<text class="text-[28rpx] text-[#333]">{{ item.title }}</text>
					<view class="text-[28rpx] text-[#333]">{{ item.value }}</view>
				</view>
			</view> -->

			<!-- <view v-for="(item, index) in verifyInfo.value.content.diy" :key="index"
				class="card-template mt-[var(--top-m)] sidebar-margin">
				<view class="title">{{ item.title }}</view>
				<view class="card-template-item justify-between" v-for="(subItem, subIndex) in item.list" :key="subIndex">
					<text class="text-[28rpx] text-[#333]">{{ subItem.title }}</text>
					<text class="text-[28rpx] text-[#333]">{{ subItem.value }}</text>
				</view>
			</view> -->

			<view
				class="fixed bottom-[30rpx] primary-btn-bg text-[#fff] flex-center !text-[26rpx] rounded-[50rpx] h-[80rpx] left-[20rpx] right-[20rpx] font-500"
				@click="verifyFn">确定</view>
		</block>
		<loading-page :loading="loading"></loading-page>
	</view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app'
import { img, redirect, getToken } from '@/utils/common';
import { getVerifierInfo, getCheckVerifier, verify } from '@/app/api/verify'
import { t } from '@/locale'
import { skuSpecFormat } from '@/utils/formatting'
import { useGoods } from '@/hooks/useGoods'


const diyGoods = useGoods();

const loading = ref(true)
const code = ref('');
onLoad((option: any) => {
	if (option.code) code.value = option.code;
	// 小程序扫码进入
	if (option.scene) {
		let sceneParams: any = decodeURIComponent(option.scene).split('&');
		if (sceneParams.length) {
			sceneParams.forEach((item: any) => {
				if (item.indexOf('code') != -1) code.value = item.split('-')[1];
			});
		}
	}
})

onShow(() => {
	if (getToken()) {
		// checkIsVerifier();
		getVerifierInfoFn();
	}
})

// 检测是否是核销员
const checkIsVerifier = () => {
	getCheckVerifier().then((res: any) => {
		if (!res.data) {
			uni.showToast({
				title: '非核销员无此权限',
				icon: 'none'
			});
			setTimeout(() => {
				if (getCurrentPages().length > 1) {
					uni.navigateBack({
						delta: 1
					});
				} else {
					redirect({
						url: '/app/pages/member/index',
						mode: 'reLaunch'
					});
				}
			}, 1000);
		} else {
			loading.value = false;
		}
	})
}
const goodsDetail: any = ref({});
const currSpec: any = ref({
	skuId: "",
	name: []
})
const matchLevelInfo = ref() //超级拼团权益

const verifyInfo = ref({})
const getVerifierInfoFn = () => {
	loading.value = true;
	getVerifierInfo({
		pickUpVerifyCode: code.value
	}).then((res: any) => {
		verifyInfo.value = res.data;
		matchLevelInfo.value = res.data.matchLevel
		if (res.data.spu) {
			formattingGoodsDetail(res.data.spu)

		}
		loading.value = false;
	}).catch(() => {
		setTimeout(() => {
			loading.value = false;
			redirect({ url: '/app/pages/verify/index', param: {}, mode: 'redirectTo' })
		}, 1000);
	})
}
const formattingGoodsDetail = (data: any) => {
	console.log(data)
	goodsDetail.value.goods = data; //商品信息
	goodsDetail.value.goods_id = data.spuId,
		goodsDetail.value.skuList = data.skus.map((sku: any) => {
			return {
				sku_id: sku.skuId,
				sku_image: sku.picUrl,
				price: sku.price, //零售价
				sku_spec_format: sku.properties.map((value: any) => {
					return value.valueName
				}).toString(),
			}
		})
	goodsDetail.value.goodsSpec = diyGoods.getPropertyList(data.skus).map((spec) => {
		return {
			spec_id: spec.id,
			spec_name: spec.name,
			spec_values: spec.values.map((specValue: any) => {
				return specValue.name
			}).toString()
		}
	})
	/** 原代码的接口逻辑中有默认选中的商品 故暂取第一个sku的数据为默认选中商品 */
	Object.assign(goodsDetail.value, goodsDetail.value.skuList[0])
	console.log(goodsDetail.value)
	if (!Object.keys(currSpec.value.name).length) currSpec.value.name = goodsDetail.value.sku_spec_format.split(",");
	goodsDetail.value.goodsSpec.forEach((item: any, index: any) => {
		let specName = item.spec_values.split(",");
		item.values = [];
		specName.forEach((specItem: any, specIndex: any) => {
			item.values[specIndex] = {};
			item.values[specIndex].name = specItem;
			item.values[specIndex].selected = false;
			item.values[specIndex].disabled = false;

			// 选中规格
			currSpec.value.name.forEach((currSpecItem, currSpecIndex) => {
				if (currSpecIndex == index && currSpecItem == specItem) {
					item.values[specIndex].selected = true;
				}
			})
		})
	})
	getSkuId()
	// 当前详情内容
	if (goodsDetail.value.skuList && Object.keys(goodsDetail.value.skuList).length) {
		goodsDetail.value.skuList.forEach((idItem: any, idIndex: any) => {
			if (idItem.sku_id == currSpec.value.skuId) {
				goodsDetail.value.detail = idItem;
			}
		})
	}
}
const change = (data: any, index: any) => {
	currSpec.value.name[index] = data.name;
	getSkuId(); // 刷新当前规格信息
}
const getSkuId = () => {
	goodsDetail.value.skuList.forEach((skuItem: any, skuIndex: any) => {
		if (skuItem.sku_spec_format == currSpec.value.name.toString()) {
			currSpec.value.skuId = skuItem.sku_id
		}
	})
}
let isLoading = false;
const verifyFn = () => {
	if (isLoading) return false;
	isLoading = true;

	verify(code.value, currSpec.value.skuId ? currSpec.value.skuId : undefined,
		matchLevelInfo.value ? matchLevelInfo.value.value : undefined).then((res: any) => {
			uni.showToast({
				title: '核销成功',
				icon: 'none'
			});
			setTimeout(() => {
				isLoading = false;
				redirect({ url: '/app/pages/verify/index', param: {}, mode: 'redirectTo' })
			}, 1000);
		}).catch(() => {
			isLoading = false;
		})
}
</script>

<style lang="scss" scoped></style>
